package com.jinlejia.erp.ui.house;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.HouseFollowListAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentFollowListBinding;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.widget.AutoLoadListView;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * A simple {@link Fragment} subclass.
 */
public class FollowListFragment extends Fragment implements AutoLoadListView.IonLoadMore, SwipeRefreshLayout.OnRefreshListener {

    private View view;

    HouseFollowListAdapter listAdapter;
    JSONObject jsonObject = new JSONObject();
    private int page = 1;
    private boolean mLoadingLock = false;

    ArrayList<Map<String, Object>> dataList;
    private String phoneNO = "";
    private String rscode,type,state;

    public FollowListFragment() {
        // Required empty public constructor
    }


    public static FollowListFragment newInstance(String rscode,String type,String state) {
        FollowListFragment fragment = new FollowListFragment();
        Bundle args = new Bundle();
        args.putString("rscode", rscode);
        args.putString("type", type);
        args.putString("state", state);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            rscode = getArguments().getString("rscode");
            type = getArguments().getString("type");
            state = getArguments().getString("state");
        }
    }
    private FragmentFollowListBinding binding;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_follow_list, null);
            binding = DataBindingUtil.bind(view);
            initView();
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }

        return view;
    }

    private void initView() {
        dataList = new ArrayList<>();
        listAdapter = new HouseFollowListAdapter(dataList);
        listAdapter.setOnCallListener(new HouseFollowListAdapter.OnCallListener() {
            @Override
            public void onCall(String tel) {
                phoneNO = tel;
                CallUtils.CallTel(getActivity(), phoneNO);
            }
        });

        binding.autoLoadListview.setAdapter(listAdapter);
        binding.autoLoadListview.setOnLoadmoreListener(this, getActivity());
        binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refreshLayout.setOnRefreshListener(this);
        getData();
    }

    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 20);
        jsonObject.put("pageIndex", page);
        jsonObject.put("rscode", rscode);
        jsonObject.put("type", state);
        String url;
        if (type.equals("shs")) {
            url = ApiConfig.SHS_FOLLOW_LIST;
        } else {
            url = ApiConfig.RENT_FOLLOW_LIST;
        }
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(getActivity(), response, null)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //数据列表
                            ArrayList<Map<String, Object>> list = JSON.parseObject(data.getJSONArray("list").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (null == list)
                                list = new ArrayList<>();
                            if (page == 1) {
                                dataList.clear();
                            }
                            dataList.addAll(list);
                            listAdapter.notifyDataSetChanged();
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            page--;
                        }
                        mLoadingLock = false;
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                        binding.autoLoadListview.setLoading(false);
                    }
                });
    }

    @Override
    public void onLoadMore() {
        if (mLoadingLock) {
            return;
        }
        page++;
        getData();
    }

    @Override
    public void onRefresh() {
        if (mLoadingLock) {
            return;
        }
//        mLoadingLock = true;
        page = 1;
        dataList.clear();
        getData();
    }
}
